<?php
class Product_Warehouse extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'product_warehouse',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 新建仓库产品（多个或单个）
	 * @param $product_basic_number 基础产品编号，数组或一个编号
	 * @param $warehouse_id
	 */
	static function create($product_basic_number, $warehouse_id, $shelf_position = '')
	{
		if ( ! is_array($product_basic_number))
		{
			$is_array = FALSE;
			$product_basic_number = array($product_basic_number);
		}
		else
		{
			$is_array = TRUE;
		}
		$ack = SUCCESS;
		$message = array();
		$product_warehouse = array();
		$default_warehouse_id = Warehouse::getDefaultWarehouseId();
		foreach ($product_basic_number as $number)
		{
			$product_basic_in_db = Product_Basic::find('number=?', $number)->asArray()->getOne();
			if ($product_basic_in_db)
			{
				$product_warehouse_in_db = Product_Warehouse::find('product_basic_id=? and warehouse_id=?', $product_basic_in_db['id'], $warehouse_id)->getOne();
				if ($product_warehouse_in_db['id'])
				{
					if($shelf_position != '')
					{
						$product_warehouse_in_db -> warehouse_id = $warehouse_id;
						$product_warehouse_in_db -> shelf_position = $shelf_position;
						$product_warehouse_in_db -> save();
						return true;
					}else{
						$ack = PARTIAL_FAILURE;
						$message[] = $number . ' 已存在仓库！';
						$product_warehouse[] = array('number' => $number, 'product_warehouse_id' => '');
					}
				}
				else
				{			
					$product = new Product_Warehouse();
					$product->product_basic_id = $product_basic_in_db['id'];
					$product->warehouse_id = $warehouse_id;
					$product->storage_number = ($warehouse_id == $default_warehouse_id) ? $product_basic_in_db['number'] : '';
					$product->actual_quantity = 0;
					$product->available_quantity = 0;
					$product->sold_quantity = 0;
					$product->save();
					$product_warehouse_id = mysql_insert_id();
					
					$log = new Inventory_Log();
					$log->product_basic_id = $product_basic_in_db['id'];
					$log->warehouse_id = $warehouse_id;
					$log->type = Q::ini('custom_flag/inventory_log_type/init/value');
					$log->init_quantity = 0;
					$log->in_quantity = 0;
					$log->out_quantity = 0;
					$log->cost_price = 0;
					$log->sales_price = 0;
					$log->cost_amount = 0;
					$log->sales_amount = 0;
					$log->currency_rate = 0;
					$log->currency_id = 0;
					$log->remaining_quantity = 0;
					$log->user_id = 0;
					$log->time = CURRENT_DATETIME;
					$log->save();
					
					$product_warehouse[] = array('number' => $number, 'product_warehouse_id' => $product_warehouse_id);
				}
			}
			else
			{
				$ack = PARTIAL_FAILURE;
				$message[] = $number . ' 不存在！';
				$product_warehouse[] = array('number' => $number, 'product_warehouse_id' => '');
			}
			
		}
		if ($is_array)
		{
			return array(
				'ack' => $ack,
				'message' => $message ? implode(',', $message) : '',
				'product_warehouse' => $product_warehouse
			);
		}
		else
		{
			return array(
				'ack' => ($ack == SUCCESS) ? $ack : FAILURE,
				'message' => $message ? $message[0] : '',
				'product_warehouse' => $product_warehouse[0]
			);
		}
	}
	
	static function getProductIdByWarehouseCode($code)
	{
		$products = Product_Warehouse::find('warehouse.code=?', $code)
			->joinLeft('warehouse', '', 'warehouse.id=product_warehouse.warehouse_id')
			->asArray()->getAll();
		if ($products)
		{
			$result = array();
			foreach ($products as $p)
			{
				$result[] = $p['product_basic_id'];
			}
			return $result;
		}
		else
		{
			return array();
		}
	}
	
	/**
	 * 按条件搜索产品库存信息
	 * @param $condition 条件数组
	 * @param $cp 当前页
	 * @param $ps 每页大小
	 */
	static function search($condition, $cp, $ps, $sort_order='product_warehouse.storage_number desc')
	{
		$columns = array(
			'product_warehouse.*',
			'warehouse.name as warehouse_name',
			'product_basic.name as product_name, product_basic.id as product_basic_id, product_basic.number, product_basic.purchase_price, product_basic.last_purchase_price, product_basic.sales_floor_price, product_basic.preferred_provider_id, product_basic.weight,  product_basic.name as product_basic_name, product_basic.notes as notes, product_basic.weekly_sales as product_basic_weekly_sales, product_basic.monthly_sales as product_basic_monthly_sales, product_basic.create_time as create_time, product_basic.purchase_note, product_basic.purchase_note_flag, product_basic.purchase_note_user_id, product_basic.purchase_note_time, product_basic.img_add_time',
			'product_provider.name as preferred_provider_name',
			'a.name as last_change_purchase_status_user_name, b.name as last_change_sales_status_user_name, c.name as purchase_note_user_name',
			'user.name as follow_user_name'
		);
		$where = Product_Warehouse::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Product_Warehouse::find($where)
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->joinLeft('warehouse', '', 'warehouse.id=product_warehouse.warehouse_id')
				->joinLeft('product_provider', '', 'product_provider.id=product_basic.preferred_provider_id')
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id')
				->joinLeft('user as a', '', 'a.id=product_warehouse.last_change_purchase_status_user_id')
				->joinLeft('user as b', '', 'b.id=product_warehouse.last_change_sales_status_user_id')
				->joinLeft('user as c', '', 'c.id=product_basic.purchase_note_user_id')
				->order($sort_order)->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Product_Warehouse::find($where)
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->joinLeft('warehouse', '', 'warehouse.id=product_warehouse.warehouse_id')
				->joinLeft('product_provider', '', 'product_provider.id=product_basic.preferred_provider_id')
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id')
				->joinLeft('user as a', '', 'a.id=product_warehouse.last_change_purchase_status_user_id')
				->joinLeft('user as b', '', 'b.id=product_warehouse.last_change_sales_status_user_id')
				->joinLeft('user as c', '', 'c.id=product_basic.purchase_note_user_id')
				->order($sort_order)->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$product_warehouse = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $product_warehouse,
			'pagination' => $pagination
		);
	}
	
	/**
	 * 组装搜索条件
	 * @param $condition 条件数组
	 */
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['limit']) && $condition['limit'])
		{
			if (! in_array(CURRENT_USER_ID, explode(' ', Q::ini('custom_flag/info/purchase_assistant/value'))))
			{
				$where .= ' and (user.id=' . CURRENT_USER_ID . ' or (product_provider.follow_user_id is NULL and product_basic.name is NULL and product_basic.declared_value is NULL and product_basic.declared_name_cn is NULL and product_basic.declared_name_en is NULL))';
			}
		}
		if ( ! empty($condition['follow_user_id']))
		{
			$where .= ' and product_provider.follow_user_id=' . $condition['follow_user_id'];
		}
		if ( ! empty($condition['purchase_note_user_id']))
		{
			$where .= ' and product_basic.purchase_note_user_id=' . $condition['purchase_note_user_id'];
		}
		if ( ! empty($condition['start_number']))
		{
			$where .= ' and product_basic.number like "' . $condition['start_number'] . '%"';
		}
		if ( ! empty($condition['end_number']))
		{
			$where .= ' and product_basic.number<=' . $condition['end_number'];
		}
		if (! empty($condition['product_numbers']))
		{
			$product_numbers = Q::Normalize($condition['product_numbers'], ",");
			$where .= ' and product_basic.number in (\'' . implode('\',\'', $product_numbers) . '\')';
		}
		if ( ! empty($condition['name']))
		{
			$where .= ' and product_basic.name like \'%' . $condition['name'] . '%\'';
		}
		if ( ! empty($condition['preferred_provider_name']))
		{
			$where .= ' and product_provider.name like \'%' . $condition['preferred_provider_name'] . '%\'';
		}
		if ( ! empty($condition['product_feature']))
		{
			$where .= ' and product_warehouse.product_feature like \'%' . $condition['product_feature'] . '%\'';
		}
		if ( ! empty($condition['product_categories_id']))
		{
			$product_categories_ids = Product_Categories::getOffspringById($condition['product_categories_id']);
			array_push($product_categories_ids, $condition['product_categories_id']);
			$where .= ' and product_basic.product_categories_id in (' . implode(',', $product_categories_ids) . ')';
		}
		if ( ! empty($condition['warehouse_id']))
		{
			$where .= ' and product_warehouse.warehouse_id=' . $condition['warehouse_id'];
		}
		if ( ! empty($condition['begin_create_time']))
		{
			$where .= ' and product_basic.create_time>=\'' . $condition['begin_create_time'] . ' 00:00:00\'';
		}
		if ( ! empty($condition['end_create_time']))
		{
			$where .= ' and product_basic.create_time<\'' . $condition['end_create_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_note_time']))
		{
			$where .= ' and product_basic.purchase_note_time>=\'' . $condition['begin_note_time'] . ' 00:00:00\'';
		}
		if ( ! empty($condition['end_note_time']))
		{
			$where .= ' and product_basic.purchase_note_time<\'' . $condition['end_note_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['product_number']))
		{
			$product_number = Q::normalize($condition['product_number']);
			$where .= ' and product_basic.number in(\'' . implode('\',\'', $product_number) . '\')';
		}
		if ( ! empty($condition['product_name']))
		{
			$where .= ' and product_basic.name like \'%' . $condition['product_name'] . '%\'';
		}
		if ( ! empty($condition['purchase_note']))
		{
			$where .= ' and product_basic.purchase_note like \'%' . $condition['purchase_note'] . '%\'';
		}
		if (isset($condition['purchase_actual_quantity']))
		{
			$where .= ' and product_warehouse.purchase_actual_quantity>=' . $condition['purchase_actual_quantity'];
		}
		if (isset($condition['available_quantity']) && $condition['available_quantity'] !== '' && !empty($condition['available_quantity_operator']))
		{
			$where .= ' and product_warehouse.available_quantity' . $condition['available_quantity_operator'] . $condition['available_quantity'];
		}
		if (isset($condition['actual_quantity']) && $condition['actual_quantity'] !== '' && !empty($condition['actual_quantity_operator']))
		{
			$where .= ' and product_warehouse.actual_quantity' . $condition['actual_quantity_operator'] . $condition['actual_quantity'];
		}
		if (isset($condition['weekly_sales']) && $condition['weekly_sales'] !== '' && !empty($condition['weekly_sales_operator']))
		{
			$where .= ' and product_warehouse.weekly_sales' . $condition['weekly_sales_operator'] . $condition['weekly_sales'];
		}
		if (isset($condition['monthly_sales']) && $condition['monthly_sales'] !== '' && !empty($condition['monthly_sales_operator']))
		{
			$where .= ' and product_warehouse.monthly_sales' . $condition['monthly_sales_operator'] . $condition['monthly_sales'];
		}
		if (isset($condition['average_sales']) && $condition['average_sales'] !== '' && !empty($condition['average_sales_operator']))
		{
			$where .= ' and product_warehouse.three_months_avg_sales' . $condition['average_sales_operator'] . $condition['average_sales'];
		}
		if (isset($condition['oos_days']) && $condition['oos_days'] !== '' && !empty($condition['oos_days_operator']))
		{
			$where .= ' and product_warehouse.oos_days' . $condition['oos_days_operator'] . $condition['oos_days'];
		}
		if (isset($condition['purchase_budget']) && $condition['purchase_budget'] !== '' && !empty($condition['purchase_budget_operator']))
		{
			$where .= ' and product_warehouse.purchase_budget_quantity' . $condition['purchase_budget_operator'] . $condition['purchase_budget'];
		}
		if (isset($condition['purchase_quantity']) && $condition['purchase_quantity'] !== '' && !empty($condition['purchase_quantity_operator']))
		{
			$where .= ' and product_warehouse.purchase_quantity' . $condition['purchase_quantity_operator'] . $condition['purchase_quantity'];
		}
		if (isset($condition['wholesale_quantity']) && $condition['wholesale_quantity'] !== '' && !empty($condition['wholesale_quantity_operator']))
		{
			$where .= ' and product_warehouse.wholesale_quantity' . $condition['wholesale_quantity_operator'] . $condition['wholesale_quantity'];
		}
		if ( ! empty($condition['shelf_position']))
		{
			$where .= ' and product_warehouse.shelf_position regexp \'' . $condition['shelf_position'] .'\'';
		}
		if (isset($condition['sales_status']))
		{
			$sales_status_filter = '0';
			foreach (Q::ini('custom_flag/product_sales_status') as $ss)
			{
				if (isset($condition['sales_status'][$ss['value']]) && $condition['sales_status'][$ss['value']] == $ss['value'])
				{
					$sales_status_filter .= ' or product_warehouse.sales_status=' . $ss['value'];
				}
			}
			$where .= ' and (' . $sales_status_filter . ')';
		}
		if (isset($condition['purchase_status']))
		{
			$purchase_status_filter = '0';
			foreach (Q::ini('custom_flag/product_purchase_status') as $ps)
			{
				if (isset($condition['purchase_status'][$ps['value']]) && $condition['purchase_status'][$ps['value']] == $ps['value'])
				{
					$purchase_status_filter .= ' or product_warehouse.purchase_status=' . $ps['value'];
				}
			}
			$where .= ' and (' . $purchase_status_filter . ')';
		}
		if (isset($condition['warning_status']))
		{
			$warning_status_filter = '0';
			foreach (Q::ini('custom_flag/product_warning_status') as $ws)
			{
				if (isset($condition['warning_status'][$ws['value']]) && $condition['warning_status'][$ws['value']] == $ws['value'])
				{
					$warning_status_filter .= ' or product_warehouse.warning_status=' . $ws['value'];
				}
			}
			$where .= ' and (' . $warning_status_filter . ')';
		}
		if (isset($condition['purchase_note_flag']))
		{
			$purchase_note_flag_filter = '0';
			foreach (Q::ini('custom_flag/product_basic_purchase_note_flag') as $pm)
			{
				if (isset($condition['purchase_note_flag'][$pm['value']]) && $condition['purchase_note_flag'][$pm['value']] == $pm['value'])
				{
					$purchase_note_flag_filter .= ' or product_basic.purchase_note_flag=' . $pm['value'];
				}
			}
			$where .= ' and (' . $purchase_note_flag_filter . ')';
		}
		if (isset($condition['oos']))
		{
			$where .= ' and (product_warehouse.purchase_status=' . Q::ini('custom_flag/product_purchase_status/restock/value') . ' or product_warehouse.actual_quantity < product_warehouse.sold_quantity)';
		}
		if (isset($condition['backorder']))
		{
			$where .= ' and product_warehouse.sold_quantity>product_warehouse.actual_quantity';
		}
		if (isset($condition['undone']))
		{
			$where .= ' and (product_basic.name is NULL or product_basic.name=\'\' or product_basic.preferred_provider_id is NULL or product_basic.preferred_provider_id=0 or product_basic.preferred_provider_id=\'\' or product_basic.declared_name_en is NULL or product_basic.declared_name_en=\'\' or product_basic.declared_value is NULL or product_basic.declared_value=\'\' or product_basic.declared_value=0 or product_basic.declared_name_cn is NULL or product_basic.declared_name_cn=\'\' or product_categories_id=0 or product_categories_id=\'\' or weight=0 or weight=\'\' or purchase_price is NULL or purchase_price=0 or purchase_price=\'\')';
		}
		if (isset($condition['no_follow_user']))
		{
			$where .= ' and (product_basic.preferred_provider_id is NULL or product_basic.preferred_provider_id=0)';
		}
		if ( ! empty($condition['number_or_name']))
		{
			$where .= ' and (product_basic.number like \'' . $condition['number_or_name'] . '%\' or product_basic.name like \'%' . $condition['number_or_name'] . '%\')';
		}
		if ( ! empty($condition['begin_img_add_time']))
		{
			$where .= ' and product_basic.img_add_time>=\'' . $condition['begin_img_add_time'] . ' 00:00:00\'';
		}
		if ( ! empty($condition['end_img_add_time']))
		{
			$where .= ' and product_basic.img_add_time<\'' . $condition['end_img_add_time'] . ' 23:59:59\'';
		}
		return $where;
	}
	
	/**
	 * 增加实际库存
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function actualQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set actual_quantity=actual_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少实际库存
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function actualQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set actual_quantity=actual_quantity-' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 增加可用库存
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function availableQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set available_quantity=available_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少可用库存
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function availableQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set available_quantity=available_quantity-' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 增加待发数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function soldQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set sold_quantity=sold_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少待发数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function soldQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set sold_quantity=sold_quantity-' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 增加采购录单数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseBudgetQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_budget_quantity=purchase_budget_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少采购录单数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseBudgetQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_budget_quantity=purchase_budget_quantity-' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 增加采购实际数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseActualQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' .$id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_actual_quantity=purchase_actual_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少采购实际数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseActualQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' .$id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_actual_quantity=purchase_actual_quantity-' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 增加采购数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseQuantityIncrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' .$product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_quantity=purchase_quantity+' . $quantity . ' where ' . $where);
	}
	
	/**
	 * 减少采购数量
	 * @param $id
	 * @param $product_basic_id
	 * @param $warehouse_id
	 * @param $quantity
	 */
	static function purchaseQuantityDecrease($id, $product_basic_id, $warehouse_id, $quantity)
	{
		if ($id)
		{
			$where = 'id=' . $id;
		}
		else
		{
			$where = 'product_basic_id=' .$product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_quantity=purchase_quantity-' . $quantity . ' where ' . $where);
	}
	
	static function updatePurchaseStatus($id, $product_basic_id, $warehouse_id, $purchase_status, $user_id)
	{
		if ($id)
		{
			$where = 'id=' .$id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set purchase_status=' . $purchase_status . ',last_change_purchase_status_user_id=' . $user_id . ',last_change_purchase_status_time=\'' . CURRENT_DATETIME . '\' where ' . $where);
	}
	
	static function updateSalesStatus($id, $product_basic_id, $warehouse_id, $sales_status, $user_id)
	{
		if ($id)
		{
			$where = 'id=' .$id;
		}
		else
		{
			$where = 'product_basic_id=' . $product_basic_id . ' and warehouse_id=' . $warehouse_id;
		}
		QDB::getConn()->execute('update product_warehouse set sales_status=' . $sales_status . ',last_change_sales_status_user_id=' . $user_id . ',last_change_sales_status_time=\'' . CURRENT_DATETIME . '\' where ' . $where);
	}
	
	/**
	 * 海外仓产品库存编码获取
	 * @param $proudct_basic_id
	 */
	static function getCK1StorageNumber($product_basic_id)
	{
		$judge_result = Product_Warehouse::judgeGetCK1StorageNumber($product_basic_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$warehouse_id = Warehouse::getDefaultWarehouseId();
			$overseas_product = Product_Warehouse::find('product_warehouse.product_basic_id=? and warehouse.is_default<>' . $warehouse_id, $product_basic_id)
				->joinLeft('product_basic', 'product_basic.number, product_basic.weight, product_basic.product_categories_id, product_basic.declared_value, product_basic.declared_name_en', 'product_basic.id=product_warehouse.product_basic_id')
				->joinleft('product_material', 'product_material.specifications', 'product_material.id=product_warehouse.product_material_id')
				->joinLeft('warehouse', 'warehouse.code as warehouse_code', 'warehouse.id=product_warehouse.warehouse_id')
				->asArray()->getOne();
			$soap_client = new SoapClient(Q::ini('custom_api/express_wsdl'));
			if ($overseas_product['storage_number'])
			{
				return array('ack' => FAILURE, 'message' => 'storage number is already exists');
			}
			else
			{
				$get_model_request = array(
					'Token' => Q::ini('custom_api/ck1_express_api_token'),
					'UserKey' => Q::ini('custom_api/ck1_express_api_key'),
					'MessageID' => CURRENT_TIMESTAMP,
					'SKU' => $overseas_product['number']
				);
				$model_in_ck1 = $soap_client->ProductGetModel(array('request'=>$get_model_request));
				if ($model_in_ck1->ProductGetModelResult->Ack == 'Failure')
				{
					$specifications = explode('*', $overseas_product['specifications']);
					$ancestor = Product_Categories::getAncestorById($overseas_product['product_categories_id']);
					$category = $ancestor[0]['name'];
					$add_model_request = array(
							'Token' => Q::ini('custom_api/ck1_express_api_token'),
							'UserKey' => Q::ini('custom_api/ck1_express_api_key'),
							'MessageID' => CURRENT_TIMESTAMP,
							'ModelDetail' => array(
									'Category' => $category,
									'Custom' => $overseas_product['number'],
									'DeclareName' => $overseas_product['declared_name_en'],
									'DeclareValue' => $overseas_product['declared_value'],
									'Description' => '',
									'Packing' => array(
											'Length' => isset($specifications[0]) ? trim($specifications[0]) : 0,
											'Width' => isset($specifications[1]) ? trim($specifications[1]) : 0,
											'Height' => isset($specifications[2]) ? trim($specifications[2]) : 0
									),
									'ProductFlag' => 'Normal',
									'Weight' => $overseas_product['weight'],
									'Warning' => 0,
									'SKU' => $overseas_product['number'],
							)
					);
					$result = $soap_client->ProductAddModel(array('request' => $add_model_request));
				}
				$get_store_request = array(
						'Token' => Q::ini('custom_api/ck1_express_api_token'),
						'UserKey' => Q::ini('custom_api/ck1_express_api_key'),
						'MessageID' => CURRENT_TIMESTAMP,
						'Warehouse' => $overseas_product['warehouse_code'],
						'SKU' => $overseas_product['number']
				);
				$result = $soap_client->ProductGetStorageNo(array('request'=>$get_store_request));
				if ($result->ProductGetStorageNoResult->Ack == 'Success')
				{
					QDB::getConn()->execute('update product_warehouse set storage_number=\''.$result->ProductGetStorageNoResult->StorageNo.'\' where id='.$overseas_product['id']);
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 判断是否能够获取库存编码
	 * @param $product_basic_id
	 */
	static function judgeGetCK1StorageNumber($product_basic_id)
	{
		$warehouse_id = Warehouse::getDefaultWarehouseId();
		$overseas_product = Product_Warehouse::find('product_warehouse.product_basic_id=? and warehouse.is_default<>' . $warehouse_id, $product_basic_id)
			->joinLeft('warehouse', '', 'warehouse.id=product_warehouse.warehouse_id')
			->joinleft('product_material', 'product_material.specifications', 'product_material.id=product_warehouse.product_material_id')
			->asArray()->getOne();
		if ( ! empty($overseas_product))
		{
			if (isset($overseas_product['specifications']))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'product material specifications is null!');
			}
			
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'product is not overseas warehouse products');
		}
	}
	
	/**
	 * 判断产品是否可用，否则使之可用
	 * @param 产品id $product_basic_id
	 * @param 仓库id $warehouse_id
	 */
	static function checkProductAvailable($product_basic_id, $warehouse_id)
	{
		$default_warehouse_id = Warehouse::getDefaultWarehouseId();
		$product_in_db = Product_Basic::find('product_basic.id=?', $product_basic_id)
			->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $default_warehouse_id)
			->asArray()->getOne();
		if ($product_in_db)
		{
			Product_Warehouse::create($product_in_db['number'], $warehouse_id);
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 判断产品是否存在
	 * @param $product_warehouse.id
	 */
	static function checkExists($product_basic_number, $warehouse_id)
	{
		$wrong_number = array();
		foreach ($product_basic_number as $pbn)
		{
			$in_db = self::find('product_basic.number=? and product_warehouse.warehouse_id=?', $pbn, $warehouse_id)
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->setColumns('product_warehouse.id')->asArray()->getOne();
			if ( ! $in_db)
			{
				$wrong_number[] = $pbn;
			}
		}
		if ($wrong_number)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => 'partial not exists', 'not_exists' => $wrong_number);
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 修改产品销售或采购状态
	 */
	static function multiUpdateProductstatus($product_basic_number, $warehouse_id, $option, $update_status)
	{
		foreach ($product_basic_number as $pbn)
		{
			$product_warehouse = self::find('product_basic.number=? and product_warehouse.warehouse_id=?', $pbn, $warehouse_id)
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->getOne();
			if ($product_warehouse['id'])
			{
				if ($option == 'sales')
				{
					$product_warehouse->sales_status = $update_status;
					$product_warehouse->last_change_sales_status_time = CURRENT_DATETIME;
					$product_warehouse->last_change_sales_status_user_id = CURRENT_USER_ID;
				}
				if ($option == 'purchase')
				{
					$product_warehouse->purchase_status = $update_status;
					$product_warehouse->last_change_purchase_status_time = CURRENT_DATETIME;
					$product_warehouse->last_change_purchase_status_user_id = CURRENT_USER_ID;
				}
				$product_warehouse->save();
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/*
	 * 修改产品的警告状态
	 */
	static function UpdateProductWarningStatus($product_basic_number, $warehouse_id, $option = 'handled')
	{
		foreach ($product_basic_number as $n)
		{
			$product_warehouse = Self::find('storage_number=? and warehouse_id=?', $pbn, $warehouse_id)->getOne();
			if ($product_warehouse['id'])
			{
				if ($option == 'handled')
				{
					$product_warehouse->warning_status = Q::ini('custom_flag/product_warning_status/handled/value');
				}
				if ($option == 'normal')
				{
					$product_warehouse->warning_status = Q::ini('custom_flag/product_warning_status/normal/value');
				}
				$product_warehouse->save();
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
}